package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.model.Member;

public class MemberDAO {
	
	public static final String url = "jdbc:mysql://127.0.0.1/yujiaguan?useUnicode=true&characterEncoding=UTF-8";  
    public static final String name = "com.mysql.jdbc.Driver";  
    public static final String user = "root";  
    public static final String password = "123456";
    public static Connection conn = null;  
	
	public MemberDAO() {
		
		try {  
            Class.forName(name); 
            if (conn == null) {
            	conn = DriverManager.getConnection(url, user, password); 
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
		
	}
	
	public Member creatMember(Member member) {
		
		
		PreparedStatement pst = null; 
		Member mem = null;
    
    	
    	String sql = "insert into member(NAME,ADDRESS,JOB) values('"+
    			member.getName()+"','"+member.getAddress()+"','"+member.getJob()+"')";
    	
    	try {
    		pst = conn.prepareStatement(sql);
    		pst.execute(sql);
    		mem = selectMember(member.getName());
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    	}  finally {
    		return mem;
    	}
    	
	}
	
	public Member selectMember(String name) {
		String checkTheName = "select * from member where NAME = '"+ name +"'";
    	PreparedStatement check = null;
    	ResultSet ret = null;
    	Member member = null;
    	
    	try {
    		check = conn.prepareStatement(checkTheName);
    		ret = check.executeQuery(checkTheName);
    		if (ret.next()) {
    			member = new Member(ret.getInt(1),
    					ret.getString(2),ret.getString(3),ret.getString(4));
    		}
    	} catch (SQLException e1) {
    		e1.printStackTrace();
    		
    	} finally {
    		return member;
    	}
	}

}
